-- UICreationGate
-- Created by huanghr Nov/11/2015
-- 创世之门

require "game/ui/form/equips/UIEquipTooltip"
require "game/ui/form/equips/UIEquips"

-- UICreationGate 继承自Layer
UICreationGate = class("UICreationGate", function()
    return cc.Layer:create();
end);

function UICreationGate.create(pos, openType)
    return UICreationGate.new(pos, openType);
end

-- 内部函数声明
local resize;
local MAX_SUBMIT_NUM = 7;
local MAX_DESC_NUM = 4;
local CreationGateUnreal = 31;

-- 6把钥匙ID = {命运の钥, 知识の钥, 时光の钥, 永恒の钥, 天空の钥, 毁灭の钥， 战争の钥}
local keyIds = FormulaM.invoke("GET_CREATIONGATE_KEYS");

-- 构造函数
function UICreationGate:ctor(pos, openType)
    self:setName("UICreationGate");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/blacksmith/CreationGate.csb");
    self:addChild(node);
    self.node = node;

    self.pos = pos;
    self.openType = openType or "creation_gate";

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.submited = {};

    self.gridData = DungeonM.getGridByPos(pos);

    local options = self.gridData.keys or {};

    if options.e then
        options = options:toTable();
    end
    printTable(options, "UICreationGate, options");

    self.submitedKeys = options;
    self.gridData.keys = options;

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UICreationGate:registerEventCallback()
    -- 关注工坊放入装备的事件
    EventMgr.register("UICreationGate", event.BLACKSMITH_INPUT_EQUIP, function(args)
        self:whenInputEquip(args);
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UICreationGate 界面析构清理");
            EventMgr.removeAll("UICreationGate");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
                UIDungeonMgr:getCurLevel():showTop();
            end
        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
                UIDungeonMgr:getCurLevel():hideTop();
            end
        end
    end);
end

-- 注册点击事件
function UICreationGate:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UICreationGate");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册装备点击格点击事件，固定3个
    for index = 1, MAX_SUBMIT_NUM do
        local frame = findChildByName(self.node, string.format("CT/key_node%d/frame_bg", index));
        frame.index = index;
        local function onEquipClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");

                -- 如果已经提交则不能点击
                if self.isInputed == true then
                    return;
                end

                -- 取出所有提交的装备的class_id
                local index = sender.index;
                local keyId = keyIds[index];
                local hasKey = false;
                local classId;
                for _, v in pairs(keyId) do
                    classId = v;
                    if table.indexOf(self.submitedKeys, v) ~= -1 then
                        return;
                    end

                    if EquipM.hasEquipment(v) then
                        hasKey = true;
                    end
                end

                if not hasKey then
                    local name = ItemM.query(classId, "name");
                    alert(string.format(getLocStr("havent_item"), name));
                    return;
                end
                -- 打开装备选择界面
                -- 传入参数：通过魔神雕像方式打开
                local uiEquip = UIEquips.create(EQUIP_OPEN_TYPE_CREATE_GATE, {["keyIds"] = keyId});
                UIMgr.getCurrentScene():addForm(uiEquip);
            end
        end
        frame:addTouchEventListener(onEquipClick);
    end
end

-- 重绘
function UICreationGate:redraw()
    local CT = findChildByName(self.node, "CT");
    local BT = findChildByName(self.node, "BT");

    -- 创世之门图标
    local creationIcon = findChildByName(self.node, "CT/icon");
    local icon = BuildingBonusM.queryBuildingView(self.gridData.class, "icon");
    creationIcon:loadTexture(getLevelItemIconPath(icon));

    -- 显示标题
    local title;
    local name = BuildingBonusM.queryBuildingView(self.gridData.class, "title");

    if type(name) == "string" and name ~= "" then
        -- 如果配置了标题，直接使用
        title = name;
    else
        -- 使用雕像名字
        title = getLocStr("creation_gate_title");
    end

    local titleLabel = findChildByName(CT, "title_node/title_label");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_CYAN, true);
    titleLabel:setString(title)
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 显示功能描述
    local desc = BuildingBonusM.queryBuildingView(self.gridData.class, "dialog");
    local descLabel = findChildByName(CT, "desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(descLabel, desc);

    self:redrawKeys();

    -- 显示返回按钮
    local btnBack = findChildByName(BT, "btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- c重绘钥匙格子
function UICreationGate:redrawKeys()
    -- 取出所有提交的装备的class_id
    local submitList = {};

    for index = 1, MAX_SUBMIT_NUM do
        local keyIcon = findChildByName(self.node, string.format("CT/key_node%d/key_icon", index));
        local frame = findChildByName(self.node, string.format("CT/key_node%d/frame_bg", index));
        frame:removeAllChildren();
        keyIcon:stopAllActions();
        local keyId = keyIds[index];
        local hasKey = false;

        for k, v in pairs(keyId) do
            keyIcon:stopAllActions();
            keyIcon:loadTexture(getItemIconPath(ItemM.query(v, "icon")));
            if table.indexOf(self.submitedKeys, v) ~= -1 then
                -- 已经提交，正常显示
                hasKey = false;
                keyIcon:setVisible(true);
                keyIcon:setOpacity(255);
                break;
            elseif EquipM.hasEquipment(v) then
                -- 需要播放呼吸动画
                hasKey = true;
                keyIcon:setVisible(true);
                keyIcon:setOpacity(80);
            else
                -- 没有钥匙，重置透明度
                keyIcon:setOpacity(80);
            end
        end

        if hasKey then
            playBubbleAnima2(keyIcon, false, 0.9);
        end
    end
end

-- 工坊放入装备的回调
function UICreationGate:whenInputEquip(args)
    local equipId = args.classId;
    local isEquiped = args.isEquiped;

    self.isInputed = true;

    -- 收集奖励信息
    BonusM.clearBonusCollect();
    BonusM.startBonusCollect();

    -- 提交当前装备
    if self.openType ~= "normal_submit" then
        DungeonActionM.go("submit_creationgate_key", 0, equipId);
    else
        DungeonActionM.go("submit_creationgate_key2", 0, equipId);
    end

    BonusM.endBonusCollect();

    self.bonusList = table.deepcopy(BonusM.getBonusCollect());
    BonusM.clearBonusCollect();

    -- 如果已经提价了6把，那么这一把就就可以进入创世之门了
    if #self.submitedKeys == 6 and self.openType ~= "normal_submit" then
        -- 进入夹层

        -- 进入前提示
        local beforeEnterTip = UnrealDungeonM.query(CreationGateUnreal, "before_enter_tip");
        if type(beforeEnterTip) == "string" and beforeEnterTip ~= "" then
            alert(beforeEnterTip);
        end

        DungeonActionM.go("start_unreal", self.pos, CreationGateUnreal);

        -- 关闭本页
        UIMgr.getCurrentScene():removeFormByName("UICreationGate");
        return;
    end

    local options = self.gridData.keys or {};

    if options.e then
        options = options:toTable();
    end

    table.insert(options, equipId);
    self.gridData.keys = options;

    self.submitedKeys = options;

    self:submitDesc();
    self:submitEffect();

    -- -- 根据当前物品Id，释放格子
    -- -- 重绘装备格
    -- self:redraw();
end

function UICreationGate:submitDesc()
    local desc = {};
    for index = 1, MAX_DESC_NUM do
        local str = getLocStr(string.format("creation_gate_tip%d", index));
        table.insert(desc, str);
    end

    local keyNum = #self.submitedKeys;
    if keyNum < 2 then
        alert(desc[1]);
    elseif keyNum < 4 then
        alert(desc[2]);
    elseif keyNum < 6 then
        alert(desc[3]);
    else
        alert(desc[4]);
    end
end

-- 播放特效
function UICreationGate:submitEffect()


    EventMgr.fire(event.CG_KEY_SUBMITED_EFFECT, {["pos"] = self.pos,});

    -- 拆分奖励,播放获得奖励的UI效果
    local splBonus = DungeonEggM.splitBonus(self.bonusList[1]);

    -- 因为按策划的需求，飞入的奖励可能是按批次的（比如：钻石奖励30个，那么每批5个，共6批飞入）
    -- 由于显示的当前数量在逻辑层一次就处理好了，由于显示要求（数量逐渐递增）
    -- 因此在这里对当前拥有的数量做一个本地缓存
    -- 只有钻石和物品才做分批次飞入效果
    local curNum;
    if type(splBonus[1]) == "number" and type(splBonus[2]) ~= "number" and splBonus[2] ~= "gem" then
        curNum = nil;
    else
        curNum = DungeonEggM.getTotleNumByType(splBonus[1]) - splBonus[1][3] * table.getn(splBonus);
    end

    -- 显示UI效果
    for i, c in pairs(splBonus) do
        if type(c) == "table" and #c > 0 then
            curNum = curNum + c[3];
            EventMgr.fire(event.CREATION_GATE_BONUS, {
                ["pos"]       = self.pos,
                ["bonusList"] = c,
                ["curNum"]    = curNum,
                ["index"]     = i,
            });
        else
            EventMgr.fire(event.CREATION_GATE_BONUS, {
                ["pos"]       = self.pos,
                ["bonusList"] = splBonus,
                ["curNum"]    = curNum,
                ["index"]     = i,
            });
            break;
        end
    end

    closeFormByName("UICreationGate");
end